package com.demo.miya.controller;

import com.demo.miya.controller.client.SeataMiyaClient;
import com.demo.miya.dao.mapper.UserMapper;
import com.demo.miya.model.User;
import com.demo.miya.service.seata.tcc.SeataTCCService;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * seata miya控制层
 * @author cyj
 */
@Slf4j
@RestController
public class SeataMiyaController implements SeataMiyaClient {

    @Resource
    private UserMapper userMapper;
    @Resource
    private SeataTCCService seataTCCService;

    @Override
    public void insertError(Long userId) {
        log.info("insertError userId:{}", userId);
        throw new RuntimeException("SeataMiyaController.insertError 异常");
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void insert(Long userId) {
        log.info("insert 方法，userId = {}", userId);
        User user = new User().setUserId(userId);
        userMapper.insertSelective(user);
    }

    /**
     * seata tcc模式事务，service-tx-seata服务调用
     * @param userId 用户id
     * @param sleepTime 睡眠时间
     * @throws InterruptedException 异常
     */
    public void prepare(Long userId, Long sleepTime) throws InterruptedException {
        log.info("prepare 方法， userId={}， sleepTime={}", userId, sleepTime);
        seataTCCService.prepare(null, userId, sleepTime);
    }
}
